<template>
  <div class="common-layout__personal">
    <!-- 头像 -->
    <div>
      <h3>头像</h3>
      <div>
        <el-upload
          class="avatar-uploader"
          action=""
          accept=".jpg,.jpeg,.png"
          :show-file-list="false"
          :before-upload="uploadAvatarBefore"
          style="border: 1px solid rgb(209, 209, 209)"
        >
          <div
            v-if="userInfo.headshot"
            class="back-img__cover"
            :style="{
              'background-image':
                'url(&#34;' +
                commonApi.getHeadshot(userInfo.headshot) +
                '&#34;)',
            }"
          ></div>
          <el-icon v-else class="icon">
            <Plus />
          </el-icon>
        </el-upload>
      </div>
    </div>
    <el-divider />
    <!-- 基本信息 -->
    <div>
      <h3>基本信息</h3>
      <div>
        <el-form :model="userInfo" label-width="120px">
          <el-form-item label="用户名">
            <el-col :span="10">
              <el-input v-model="userInfo.name" />
            </el-col>
          </el-form-item>
          <el-form-item label="性别">
            <el-col :span="10">
              <el-radio-group v-model="userInfo.gender">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
                <el-radio :label="2">保密</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateCommonInfo"
              >保存
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-divider />
    <!-- 用户安全 -->
    <div>
      <h3>用户安全</h3>
      <div class="safe-info">
        <el-form :model="userInfo" label-width="120px">
          <el-form-item label="手机号">
            <span v-if="!isNull(userInfo.phone)">
              <span>{{ userInfo.phone }}</span>
              <span
                class="active"
                @click="
                  () => {
                    // 更改显示
                    update.title = '修改手机号';
                    update.type = 1;
                    showUploadPvE = true;
                  }
                "
                >修改</span
              >
            </span>
            <span v-else>
              <span
                class="active"
                @click="
                  () => {
                    // 更改显示
                    update.title = '添加手机号';
                    update.type = 1;
                    showUploadPvE = true;
                  }
                "
                >添加</span
              >
            </span>
          </el-form-item>
          <el-form-item label="邮箱">
            <span v-if="!isNull(userInfo.email)">
              <span>{{ userInfo.email }}</span>
              <span
                class="active"
                @click="
                  () => {
                    // 更改显示
                    update.title = '更换邮箱';
                    update.type = 2;
                    showUploadPvE = true;
                  }
                "
                >修改</span
              >
            </span>
            <span v-else>
              <span
                class="active"
                @click="
                  () => {
                    // 更改显示
                    update.title = '添加邮箱';
                    update.type = 2;
                    showUploadPvE = true;
                  }
                "
                >添加</span
              >
            </span>
          </el-form-item>

          <el-form-item label="密码">
            <span>
              <span>***********</span>
              <span
                class="active"
                @click="
                  () => {
                    // 更改显示
                    update.title = '修改密码';
                    update.type = 3;
                    showUploadPvE = true;
                  }
                "
                >修改</span
              >
            </span>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <!-- 修改密码，手机号或邮箱 -->
  <el-dialog
    v-model="showUploadPvE"
    width="400px"
    center
    align-center
    :title="update.title"
  >
    <div>
      <el-form :model="update.data" label-width="70px">
        <el-form-item label="验证方式">
          <el-input
            placeholder="请输入手机号或邮箱"
            v-model="update.data.account"
          >
            <template #append>
              <el-button @click="sendCode(update.data.account!)"
                >获取验证码</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-col :span="12">
            <el-input
              placeholder="请输入验证码"
              v-model="update.data.code"
              maxlength="6"
            />
          </el-col>
        </el-form-item>
        <!-- 手机号 -->
        <template v-if="update.type === 1">
          <el-form-item label="新手机号">
            <el-input placeholder="请输入手机号" v-model="update.data.phone">
              <template #append>
                <el-button @click="sendCode(update.data.phone!)">
                  获取验证码
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码">
            <el-col :span="12">
              <el-input
                placeholder="请输入验证码"
                v-model="update.data.secondCode"
              />
            </el-col>
          </el-form-item>
        </template>
        <!-- 邮箱 -->
        <template v-else-if="update.type === 2">
          <el-form-item label="新邮箱">
            <el-input placeholder="请输入邮箱" v-model="update.data.email">
              <template #append>
                <el-button @click="sendCode(update.data.email!)"
                  >获取验证码</el-button
                >
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="验证码">
            <el-col :span="12">
              <el-input
                placeholder="请输入验证码"
                v-model="update.data.secondCode"
              />
            </el-col>
          </el-form-item>
        </template>
        <!-- 密码 -->
        <template v-else>
          <el-form-item label="新密码">
            <el-input
              placeholder="请输入密码"
              v-model="update.data.password"
              type="password"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码">
            <el-input
              placeholder="请输入密码"
              v-model="confirmPwd"
              type="password"
            ></el-input>
          </el-form-item>
        </template>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showUploadPvE = false">取消</el-button>
        <el-button type="primary" @click="updateSafeInfo"> 修改 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { LoginInfo, SafeInfo, User, CommonInfo } from "@/types/user";
import userApi from "@/api/user";
import commonApi from "@/api/common";
import { Plus } from "@element-plus/icons-vue";
import { UploadRawFile } from "element-plus";
import { errorNotify, isNull, successNotify } from "@/utils/common";
import Request from "@/assets/request/index";

const route = useRoute();
const userInfo = ref(<User>{});
const showUploadPvE = ref<boolean>(false);
const update = ref({
  title: "添加新手机",
  type: 1, // 1:手机，2:邮箱，3:密码
  data: <SafeInfo>{},
});
const confirmPwd = ref<string>("");

const getUserInfo = async (userId: string) => {
  const { code, data } = await Request.request<User>({
    method: "GET",
    url: `/user/${userId}`,
  });
  if (code === 0) {
    userInfo.value = data;
  }
};


const watchRoute = watch(
  () => route.params.id,
  (val) => {
    getUserInfo(val + "");
  },
  { immediate: true }
);

// 发送验证码
const sendCode = (account: string) => {
  if (isNull(account)) {
    return;
  }
  commonApi.sendCode(account!).then((res) => {
    if (res.data.code === 0) {
      successNotify(res.data.data);
    }
  });
};

// 上传头像
const uploadAvatarBefore = (rawFile: UploadRawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    errorNotify("图片大小不能超过2MB");
    return false;
  }
  let formData = new FormData();
  formData.append("file", rawFile);
  commonApi.uploadHeadshot(formData).then((res) => {
    // 获取文件名
    if (res.data.code === 0) {
      userInfo.value.headshot = res.data.data;
    }
  });
  return false;
};

// 修改一般信息
const updateCommonInfo = () => {
  let params: CommonInfo = {
    name: userInfo.value.name,
    gender: userInfo.value.gender,
  };
  userApi.updateCommonInfo(params).then((res) => {
    if (res.data.code === 0) {
      successNotify("修改成功");
    }
  });
};

// 修改敏感信息
const updateSafeInfo = () => {
  let data = update.value.data;
  // 若是更改密码，则判断两次密码输入是否一致
  if (update.value.type === 3) {
    if (isNull(data.password)) {
      errorNotify("密码不能为空");
      return;
    }
    if (data.password !== confirmPwd.value) {
      errorNotify("密码不一致");
      return;
    }
  }
  userApi.updateSensitive(data).then((res) => {
    if (res.data.code === 0) {
      successNotify("修改成功");
      if (update.value.type === 1) {
        userInfo.value.phone = update.value.data.phone!;
      } else if (update.value.type === 2) {
        userInfo.value.email = update.value.data.email!;
      }
      update.value.data = <SafeInfo>{};
      showUploadPvE.value = false;
    }
  });
};

onUnmounted(() => {
  watchRoute();
});
</script>

<style lang="scss" scoped></style>

<style lang="scss">
.common-layout__personal {
  padding-left: 50px;
  padding-right: 200px;

  & > div {
    margin: 20px;
  }

  .avatar-uploader {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    overflow: hidden;
    margin-left: 50px;

    & > * {
      position: relative;
      height: 100%;
      width: 100%;
    }

    .back-img__cover {
      width: 100%;
      height: 100%;
    }
  }

  .safe-info {
    span > span {
      &:first-child {
        font-size: 13px;
        margin-right: 10px;
      }

      &.active {
        color: #409eff;
        font-size: 13px;
        text-decoration: underline;
        cursor: pointer;
      }
    }
  }
}
</style>
